package com.ruoyi.flowable.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.flowable.config.SpringContextHolder;
import com.ruoyi.members.domain.SysMembers;
import com.ruoyi.members.service.ISysMembersService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 转会流程任务监听器
 * 根据流程变量中的申请信息，将申请人的部门(deptId)更新为目标部门
 */
@Component
public class MembersTransferTaskListener implements TaskListener {
    @Override
    public void notify(DelegateTask delegateTask) {
        // 仅在审批通过时更新。要求审批提交时在流程变量中传入 action=approve
        Object action = delegateTask.getVariable("action");
        if (action == null || !"approve".equals(String.valueOf(action))) {
            return;
        }
        // 从流程变量中获取申请对象（提交流程时以 commonClass 传入）
        Object obj = delegateTask.getVariable("commonClass");
        if (!(obj instanceof SysMembers)) {
            return;
        }
        SysMembers apply = (SysMembers) obj;

        // 目标部门ID
        Long targetDeptId = apply.getDeptId();
        if (targetDeptId == null) {
            return;
        }

        // 通过 Spring 上下文获取 service bean
        ISysMembersService membersService = SpringContextHolder.getBean("sysMembersServiceImpl", ISysMembersService.class);

        // 根据申请人 userId 定位其会员记录，并将 deptId 更新为申请的目标部门
        List<SysMembers> list = membersService.list(new LambdaQueryWrapper<>(SysMembers.class)
                .eq(SysMembers::getUserId, apply.getUserId()));
        if (list == null || list.isEmpty()) {
            return;
        }
        SysMembers db = list.get(0);
        db.setDeptId(targetDeptId);
        membersService.updateById(db);
    }
}


